package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    IUserService userService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    IBlogService blogService;

    @Resource
    IFollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = this.getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        queryBlogUser(blog);
        return Result.ok(blog);
    }

    @Override
    public Result updateLike(Long id) {
        // 1. 判断当前用户是否登陆
        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            return Result.fail("请先登陆");
        }
        // 2. 判断登陆用户是否已经给Blog ID点赞
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        // Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        if (score == null) {
            // 3.1 如果没有点赞，进行点赞
            LambdaUpdateWrapper<Blog> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Blog::getId, id);
            wrapper.setSql("liked = liked + 1");
            this.update(wrapper);
            stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            // stringRedisTemplate.opsForSet().add(key, userId.toString());
            return Result.ok("点赞成功");
        } else {
            // 3.2 如果没有点赞，进行取消
            LambdaUpdateWrapper<Blog> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Blog::getId, id);
            wrapper.setSql("liked = liked - 1");
            this.update(wrapper);
            stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            // stringRedisTemplate.opsForSet().remove(key, userId.toString());
            return Result.ok("取消点赞成功");
        }
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
            .orderByDesc("liked")
            .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result likesTopN(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> set = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(set == null || set.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = set.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids);
        wrapper.last("ORDER BY FIELD(id, " + idStr + ")");
        List<User> list = userService.list(wrapper);
        List<UserDTO> collect = list.stream().map((item) -> {
            return BeanUtil.copyProperties(item, UserDTO.class);
        }).collect(Collectors.toList());

        return Result.ok(collect);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2. 保存探店博文
        boolean isSuccess = blogService.save(blog);
        if(!isSuccess) {
            return Result.fail("新增笔记失败");
        }
        // 3. 进行推送 查询当前用户的搜索粉丝
        List<Follow> list = followService.list(
            new LambdaQueryWrapper<Follow>()
                .eq(Follow::getFollowUserId, user.getId())
        );
        for (Follow follow : list) {
            // 进行推送
            String key = RedisConstants.FEED_KEY + follow.getUserId();
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result getFollowMsg(Long max, Long offset) {
        Long userId = UserHolder.getUserId();
        String key = RedisConstants.FEED_KEY + userId;

        // 1. 获取当前的set
        Set<ZSetOperations.TypedTuple<String>> set = stringRedisTemplate.opsForZSet().
            // 最小值 最大值 偏移 数量
            reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        // 2. 实现滚动分页
        // 2.1 如果是空就返回空
        if(set == null || set.isEmpty()) {
            return Result.ok();
        }
        // 3. 解析数据，找到滚动分页的位置
        // 3.1 先找最小值
        long minTime = 0;
        ArrayList<Long> ids = new ArrayList<>(set.size());
        for (ZSetOperations.TypedTuple<String> tuple : set) {
            minTime = tuple.getScore().longValue();
            ids.add(Long.valueOf(tuple.getValue()));
        }
        // 3.2 找最小值的次数
        int os = 0;
        for (ZSetOperations.TypedTuple<String> tuple : set) {
            if(tuple.getScore().longValue() == minTime) {
                os++;
            }
        }
        // 4. 根据ID查询Blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> list = this.list(
            new LambdaQueryWrapper<Blog>()
                .in(Blog::getId, ids)
                .last("ORDER BY FIELD(id, " + idStr + ")")
        );
        for (Blog blog : list) {
            // 查询相关用户和是否被点赞
            queryBlogUser(blog);
        }

        // 5. 设置结果
        ScrollResult r = new ScrollResult();
        r.setList(list);
        r.setOffset(os);
        r.setMinTime(minTime);
        return Result.ok(r);
    }

    private void queryBlogUser(Blog blog) {
        User user = userService.getById(blog.getUserId());
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        // 判断是否已经点赞
        if (UserHolder.getUser() == null)
            return;
        Long currentId = UserHolder.getUser().getId();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, currentId.toString());
        blog.setIsLike(score != null);
    }
}
